package com.yunchen.BooksManagementSystem.login.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunchen.BooksManagementSystem.login.entity.Code;
import com.yunchen.BooksManagementSystem.login.entity.User;
import com.yunchen.BooksManagementSystem.login.service.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;



/**
 * @创建人
 * @创建时间
 * @描述
 */
@WebServlet(name = "LoginServlet",value = "/LoginServlet")
public class LoginServlet extends HttpServlet {

    LoginServiceImpl loginServices=new LoginServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter pw = resp.getWriter();

        BufferedReader br = req.getReader();
        StringBuilder builder=new StringBuilder();
        // String params= br.readLine();
        String line=null;
        while ((line=br.readLine())!=null){
            builder.append(line);
        }
        System.out.println(builder);
        User user = JSON.parseObject(String.valueOf(builder),User.class);
        System.out.println(user);

        if(user.getUserId() != null && !user.getUserId().equals(" ")){
            if (loginServices.isLogin(user.getUserId(), user.getPassword())){
                if(loginServices.isAdm(user.getUserId())){
                    Code code = new Code(0,"登陆成功（管理员）",user.getUserId(),"root");
                    String json = JSONObject.toJSONString(code);
                    pw.println(json);
                }else{
                    Code code = new Code(1,"登陆成功",user.getUserId(),"user");
                    String json = JSONObject.toJSONString(code);
                    pw.println(json);
                    //resp.setHeader("Authorization", createToken(id,pwd));

                }
            }else {
                Code code = new Code(-2,"账号或密码错误");
                String json = JSONObject.toJSONString(code);
                pw.println(json);

            }
        }else {
            Code code = new Code(-1,"账号不能为空");
            String json = JSONObject.toJSONString(code);
            pw.println(json);
        }
    }




}
